// 设置对话框主组件
// 提供设置界面的主框架，包括分类导航和内容区域

import React, { useState, useEffect } from 'react';
import { X, Search, RotateCcw, Download, Upload, HelpCircle } from 'lucide-react';
import { useSettingsStore } from '../../stores/settingsStore';
import { SettingsCategory } from '../../types/settings';
import { SettingsNavigation } from './SettingsNavigation';
import { SettingsContent } from './SettingsContent';
import { SettingsSearch } from './SettingsSearch';
import { ResetConfirmDialog, createResetConfirmProps } from './components/ResetConfirmDialog';
import { SettingsHelp } from './components/SettingsHelp';

interface SettingsDialogProps {
  isOpen: boolean;
  onClose: () => void;
  initialCategory?: SettingsCategory;
}

export const SettingsDialog: React.FC<SettingsDialogProps> = ({
  isOpen,
  onClose,
  initialCategory
}) => {
  const {
    activeCategory,
    setActiveCategory,
    isDirty,
    searchQuery,
    resetAllSettings,
    exportSettings,
    importSettings
  } = useSettingsStore();

  const [resetConfirm, setResetConfirm] = useState<{
    isOpen: boolean;
    type: 'single' | 'category' | 'all';
    settingName?: string;
    categoryName?: string;
    onConfirm: () => void;
  }>({
    isOpen: false,
    type: 'all',
    onConfirm: () => {}
  });
  const [isImporting, setIsImporting] = useState(false);
  const [showHelp, setShowHelp] = useState(false);

  // 设置初始分类
  useEffect(() => {
    if (initialCategory && isOpen) {
      setActiveCategory(initialCategory);
    }
  }, [initialCategory, isOpen, setActiveCategory]);

  // 显示重置确认对话框
  const showResetConfirmDialog = () => {
    const props = createResetConfirmProps('all');
    setResetConfirm({
      isOpen: true,
      type: 'all',
      onConfirm: () => {
        resetAllSettings();
        setResetConfirm(prev => ({ ...prev, isOpen: false }));
      }
    });
  };

  // 处理导出设置
  const handleExportSettings = () => {
    const settings = exportSettings();
    const blob = new Blob([JSON.stringify(settings, null, 2)], {
      type: 'application/json'
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `codegraph-settings-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  // 处理导入设置
  const handleImportSettings = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json';
    input.onchange = async (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file) return;

      setIsImporting(true);
      try {
        const text = await file.text();
        const data = JSON.parse(text);
        const success = await importSettings(data);
        if (success) {
          // 显示成功消息
          console.log('Settings imported successfully');
        } else {
          // 显示错误消息
          console.error('Failed to import settings');
        }
      } catch (error) {
        console.error('Invalid settings file:', error);
      } finally {
        setIsImporting(false);
      }
    };
    input.click();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="w-full max-w-6xl h-full max-h-[90vh] bg-white dark:bg-gray-900 rounded-lg shadow-xl flex flex-col">
        {/* 标题栏 */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center space-x-4">
            <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
              设置
            </h2>
            {isDirty && (
              <span className="px-2 py-1 text-xs bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded">
                有未保存的更改
              </span>
            )}
          </div>
          
          <div className="flex items-center space-x-2">
            {/* 工具按钮 */}
            <button
              onClick={handleExportSettings}
              className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800"
              title="导出设置"
            >
              <Download className="w-4 h-4" />
            </button>
            
            <button
              onClick={handleImportSettings}
              disabled={isImporting}
              className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800 disabled:opacity-50"
              title="导入设置"
            >
              <Upload className="w-4 h-4" />
            </button>
            
            <button
              onClick={showResetConfirmDialog}
              className="p-2 text-gray-500 hover:text-red-600 dark:text-gray-400 dark:hover:text-red-400 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800"
              title="重置所有设置"
            >
              <RotateCcw className="w-4 h-4" />
            </button>

            <button
              onClick={() => setShowHelp(true)}
              className="p-2 text-gray-500 hover:text-blue-600 dark:text-gray-400 dark:hover:text-blue-400 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800"
              title="帮助"
            >
              <HelpCircle className="w-4 h-4" />
            </button>

            <button
              onClick={onClose}
              className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>

        {/* 搜索栏 */}
        <div className="p-4 border-b border-gray-200 dark:border-gray-700">
          <SettingsSearch />
        </div>

        {/* 主内容区域 */}
        <div className="flex flex-1 overflow-hidden">
          {/* 左侧导航 */}
          {!searchQuery && (
            <div className="w-64 border-r border-gray-200 dark:border-gray-700 overflow-y-auto">
              <SettingsNavigation
                activeCategory={activeCategory}
                onCategoryChange={setActiveCategory}
              />
            </div>
          )}

          {/* 右侧内容 */}
          <div className="flex-1 overflow-y-auto">
            <SettingsContent />
          </div>
        </div>

        {/* 底部操作栏 */}
        <div className="flex items-center justify-between p-4 border-t border-gray-200 dark:border-gray-700">
          <div className="text-sm text-gray-500 dark:text-gray-400">
            {isDirty ? '设置已修改，将自动保存' : '所有设置已保存'}
          </div>
          
          <div className="flex items-center space-x-2">
            <button
              onClick={onClose}
              className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-md"
            >
              关闭
            </button>
          </div>
        </div>
      </div>

      {/* 重置确认对话框 */}
      <ResetConfirmDialog
        isOpen={resetConfirm.isOpen}
        title={createResetConfirmProps(resetConfirm.type, resetConfirm.settingName, resetConfirm.categoryName).title}
        message={createResetConfirmProps(resetConfirm.type, resetConfirm.settingName, resetConfirm.categoryName).message}
        resetType={resetConfirm.type}
        settingName={resetConfirm.settingName}
        categoryName={resetConfirm.categoryName}
        onConfirm={resetConfirm.onConfirm}
        onCancel={() => setResetConfirm(prev => ({ ...prev, isOpen: false }))}
      />

      {/* 帮助对话框 */}
      <SettingsHelp
        isOpen={showHelp}
        onClose={() => setShowHelp(false)}
      />
    </div>
  );
};
